package com.hl.card.pay.util;
import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.hl.card.pay.vo.PayVo;
import org.apache.commons.codec.binary.Base64;

import java.io.UnsupportedEncodingException;
import java.net.URLDecoder;
import java.net.URLEncoder;

public class Base64Tool {

  public static String encode(PayVo payVo){
       JSONObject params=new JSONObject();
       params.put("payDto",payVo);
       String paramsString= params.toJSONString();
       byte[] result = Base64.encodeBase64(paramsString.getBytes());
       System.out.println(paramsString);
       String s = new String(result);
       System.out.println("原始字符串"+s);
       String rs=s.replaceAll(" ","#").replaceAll("=","@");
      try {
          URLEncoder.encode(rs,"UTF-8");
      } catch (UnsupportedEncodingException e) {
          e.printStackTrace();
      }
      System.out.println("替换后字符串"+rs);
       return  rs;
    }

    public   static PayVo decode(String jString){
        try {
            URLDecoder.decode(jString,"UTF-8");
        } catch (UnsupportedEncodingException e) {
            e.printStackTrace();
        }
        jString.replaceAll("\\#"," ").replaceAll("\\@","=");
        byte[] re = Base64.decodeBase64(jString.getBytes());
        String s2 = new String(re);
        System.out.println(s2);
        JSONObject jsonObject=JSONObject.parseObject(s2);
        Object payDtoObject = jsonObject.get("payDto");
        String payDtoString= JSON.toJSONString(payDtoObject);
        PayVo payVo= JSONObject.parseObject(payDtoString,PayVo.class);
        return  payVo;
    }

    public static void main(String[] args) {
        PayVo payVo=new PayVo();
        payVo.setMchId("10000000");
        String s= encode(payVo);
        decode(s);
    }

}
